package com.elepro.shoppingmall.controller;

import com.elepro.shoppingmall.entity.Goods;
import com.elepro.shoppingmall.service.goods.GoodsServiceIm;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/admin")
public class GoodsManageController {
    @Resource
    private GoodsServiceIm goodsService;

    //加载所有产品
    @GetMapping("/cLoadAllGoods")
    public List<Goods> cLoadAllGoods() {
        return goodsService.sLoadAllGoods();
    }
    //增加商品
    @PostMapping("/cInsertGoods")
    public boolean cInsertGoods(Goods goods) {
        int result = goodsService.sInsertGoods(goods);
        return result == 1;
    }

    //删除产品
    @GetMapping("/cDeleteGoodsById")
    public boolean cDeleteGoodsById(long id) {
        int result = goodsService.sDeleteGoodsById(id);
        return result == 1;
    }

    //修改产品
    @PostMapping("/cUpdateGoods")
    public boolean cUpdateGoods(Goods goods) {
        System.out.println("goods ====================" + goods);
        int result = goodsService.sUpdateGoods(goods);
        return result == 1;
    }

    //上传图片
    @PostMapping("/insertImage")
    public String insertImage(@RequestParam("file") MultipartFile multipartFile) {
        uploadImage(multipartFile);
        return "http://localhost:8080/" + multipartFile.getOriginalFilename();
    }

    //图片上传
    public void uploadImage(MultipartFile multipartFile) {
        String filename = multipartFile.getOriginalFilename();
        String dirPath = "D:/image/";
        File filePath = new File(dirPath);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        try {
            multipartFile.transferTo(new File(dirPath + filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
